package com.neusoft.elmboot.service.Impl;

import java.time.LocalDateTime;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.neusoft.elmboot.mapper.TokenMapper;
import com.neusoft.elmboot.po.Token;
import com.neusoft.elmboot.service.TokenService;
import com.neusoft.elmboot.util.CommonUtil;

@Service
public class TokenServiceImpl implements TokenService{

	@Autowired
	private TokenMapper tokenMapper;
	
	@Override
	public String getToken(String publicKeyStr) {
		Token token = new Token();
		String tokenId = null;
		while(tokenMapper.getToken(tokenId)!=0) {
			tokenId = CommonUtil.getUUID_8();
		}
		token.setFrontPublicKey(publicKeyStr);
		token.setTokenId(tokenId);
		token.setTime(LocalDateTime.now());
		tokenMapper.saveToken(token);
		//KeyPair keyPair = RSAUtil.generateKeyPair();
		//String backPublicKey = Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded());
		//String backPrivateKey = Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded());
		//String key = publicKeyStr.replace('_', '+').replace('-', '/');
		//return(RSAUtil.encryptMessageWithPublicKey(key, token) + "/t" + "backPubliceKey");
		return token.getTokenId();
	}
	public String getTokenByUserById(Token token) {
		if(tokenMapper.getTokenById(token).getTime().plusMinutes(30).isAfter(LocalDateTime.now())) {
			tokenMapper.deleteToken(token);
			return null;
		}else {
			return tokenMapper.getTokenById(token).getFrontPublicKey();
		}
	}
}